<template>
  <div class="products-container">
    <div class="header">
      <h2>商品管理</h2>
    </div>

    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="商品名称">
          <el-input v-model="searchForm.name" placeholder="请输入商品名称" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item label="商品分类">
          <el-select v-model="searchForm.categoryId" placeholder="请选择分类" clearable style="width: 150px">
            <el-option v-for="category in categories" :key="category.id" :label="category.name" :value="category.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="砍价状态">
          <el-select v-model="searchForm.isBargain" placeholder="请选择状态" clearable style="width: 120px">
            <el-option label="支持砍价" :value="1" />
            <el-option label="不支持砍价" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon>
              <Search />
            </el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon>
              <Refresh />
            </el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="table-card">
      <el-table v-loading="loading" :data="products" stripe style="width: 100%" :row-key="(row) => row.id">
        <el-table-column prop="id" label="ID" width="50" />
        <el-table-column label="商品图片" width="auto">
          <template #default="{ row }">
            <el-image :src="row.coverList || '/placeholder.png'" :preview-src="row.coverList" fit="cover"
              style="width: 60px; height: 60px; border-radius: 4px" />
          </template>
        </el-table-column>
        <el-table-column prop="name" label="商品名称" min-width="150" show-overflow-tooltip />
        <el-table-column prop="categoryId" label="类别" width="auto">
          <template #default="{ row }">
            {{ getCategoryName(row.categoryId) }}
          </template>
        </el-table-column>
        <el-table-column prop="price" label="价格" width="auto">
          <template #default="{ row }">
            <span class="price">¥{{ row.price }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="inventory" label="库存" width="auto" />
        <el-table-column prop="isBargain" label="能否砍价" width="auto">
          <template #default="{ row }">
            <el-tag :type="row.isBargain === true ? 'success' : 'info'">
              {{ row.isBargain === true ? '支持' : '不支持' }}
            </el-tag>
          </template>
        </el-table-column>


        <el-table-column prop="createTime" label="发布时间" width="160">
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button size="small" @click="handleView(row)">查看</el-button>
              <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 20, 50]"
          :total="total" layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </el-card>

    <!-- 商品详情对话框 -->
    <el-dialog v-model="detailVisible" title="商品详情" width="600px" :before-close="handleDetailClose">
      <div v-if="currentProduct" class="product-detail">
        <div class="detail-item">
          <label>商品名称：</label>
          <span>{{ currentProduct.name }}</span>
        </div>
        <div class="detail-item">
          <label>商品类别：</label>
          <span>{{ getCategoryName(currentProduct.categoryId) }}</span>
        </div>
        <div class="detail-item">
          <label>价格：</label>
          <span class="price">¥{{ currentProduct.price }}</span>
        </div>

        <div class="detail-item">
          <label>库存：</label>
          <span>{{ currentProduct.inventory }}</span>
        </div>
        <div class="detail-item">
          <label>砍价：</label>
          <span>{{ currentProduct.isBargain === true ? '支持' : '不支持' }}</span>
        </div>
        <div class="detail-item">
          <label>发布时间：</label>
          <span>{{ formatDate(currentProduct.createTime) }}</span>
        </div>
        <div class="detail-item">
          <label>商品描述：</label>
          <div class="description">{{ currentProduct.detail }}</div>
        </div>
        <!-- <div class="detail-item">
          <label>商品图片：</label>
          <div class="images">
            <el-image
              v-for="(image, index) in currentProduct.coverList"
              :key="index"
              :src="image"
              :preview-src-list="currentProduct.coverList"
              fit="cover"
              style="width: 80px; height: 80px; margin-right: 10px; border-radius: 4px"
            />
          </div>
        </div> -->
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh } from '@element-plus/icons-vue'
import type { Product, Category } from '@/types'
import { formatDate } from '@/utils/date'
import request from '@/utils/request'

// 响应式数据
const loading = ref(false)
const products = ref<Product[]>([])
const categories = ref<Category[]>([])
const currentPage = ref(1)
const pageSize = ref(5) // 与后端默认值保持一致
const total = ref(0)
const detailVisible = ref(false)
const currentProduct = ref<Product | null>(null)

// 搜索表单
const searchForm = reactive({
  name: '',
  categoryId: undefined as number | undefined,
  isBargain: undefined as number | undefined
})

// 获取商品列表
const loadProducts = async () => {
  loading.value = true
  try {
    const params: any = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      name: searchForm.name || undefined,
      categoryId: searchForm.categoryId || undefined
    }

    // 只有当选择了砍价状态时才传递参数
    if (searchForm.isBargain !== undefined) {
      params.isBargain = searchForm.isBargain
    }

    const res = await request.get('/product/list', { params }) as any
    console.log(res)
    // 后端返回的是 Page<Product> 对象，需要适配
    if (res.data.records) {
      // 如果是 MyBatis Plus 的 Page 对象
      const dataArray = Array.isArray(res.data.records) ? res.data.records : []
      products.value = dataArray
      total.value = res.data.total || 0
    } else if (res.data) {
      // 如果是自定义 PageView 对象
      const dataArray = Array.isArray(res.data.data) ? res.data.data : []
      products.value = dataArray
      total.value = res.allRow || 0
    } else {
      // 直接是数组
      const dataArray = Array.isArray(res) ? res : []
      products.value = dataArray
      total.value = dataArray.length || 0
    }
  } catch (error) {
    ElMessage.error('获取商品列表失败')
  } finally {
    loading.value = false
  }
}

const loadCategories = async () => {
  try {
    // 调用后端分类接口获取分类列表
    const response = await request.get('/category/list', {
      params: {
        pageSize: 20,
      }
    })
    console.log('分类API响应:', response)

    // 检查响应数据结构
    if (response && response.data) {
      // 确保response.data是数组
      const categoryData = Array.isArray(response.data) ? response.data :
        (response.data.data && Array.isArray(response.data.data)) ? response.data.data : []

      if (categoryData.length > 0) {
        categories.value = categoryData.filter((cat: Category) => cat.isUse)
      } else {
        throw new Error('分类数据为空')
      }
    } else {
      throw new Error('分类API响应格式错误')
    }
  } catch (error) {
    console.error('加载分类失败:', error)
    // 如果API不可用，使用默认分类
    categories.value = [
    ]
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  loadProducts()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    name: '',
    categoryId: undefined,
    isBargain: undefined
  })
  currentPage.value = 1
  loadProducts()
}

// 分页处理
const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  loadProducts()
}

const handleCurrentChange = (page: number) => {
  currentPage.value = page
  loadProducts()
}

// 查看商品详情
const handleView = (row: Product) => {
  currentProduct.value = row
  detailVisible.value = true
}



// 删除商品
const handleDelete = async (row: Product) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除商品"${row.name}"吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await request.delete(`/product/${row.id}`)
    ElMessage.success('删除成功')
    loadProducts()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 关闭详情对话框
const handleDetailClose = () => {
  detailVisible.value = false
  currentProduct.value = null
}



// 根据categoryId获取类别名称
const getCategoryName = (categoryId: number) => {
  const category = categories.value.find(cat => cat.id === categoryId)
  return category ? category.name : '未知类别'
}

// 初始化
onMounted(() => {
  // 确保数据是数组
  if (!Array.isArray(products.value)) {
    products.value = []
  }
  if (!Array.isArray(categories.value)) {
    categories.value = []
  }
  loadCategories()
  loadProducts()
})
</script>

<style scoped lang="scss">
.products-container {
  padding: 20px;

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    h2 {
      margin: 0;
      color: $text-color;
    }
  }

  .search-card {
    margin-bottom: 20px;
  }

  .table-card {
    .pagination {
      margin-top: 20px;
      text-align: right;
    }
  }

  .price {
    color: $danger-color;
    font-weight: bold;
  }

  .action-buttons {
    display: flex;
    gap: 5px;
    align-items: center;
  }

}

.product-detail {
  .detail-item {
    margin-bottom: 15px;
    display: flex;
    align-items: flex-start;

    label {
      width: 100px;
      font-weight: bold;
      color: $text-color;
    }

    span {
      flex: 1;
      color: $text-color-regular;
    }

    .description {
      flex: 1;
      color: $text-color-regular;
      line-height: 1.6;
      white-space: pre-wrap;
    }

    .images {
      flex: 1;
      display: flex;
      flex-wrap: wrap;
      gap: 10px;
    }
  }
}
</style>